<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="清单名称" prop="listName">
        <el-input
          v-model="queryParams.listName"
          placeholder="请输入清单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            label="未完成"
            value="0"
          ></el-option>
          <el-option
            label="已完成"
            value="1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:buylist:add']"
        >创建清单</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:buylist:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:buylist:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExport"
          v-hasPermi="['manage:buylist:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="buylistList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="清单名称" align="center" prop="listName" />
      <el-table-column label="清单创建时间" align="center" prop="createTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="清单更新时间" align="center" prop="updateTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="清单状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'danger' : ''">{{ scope.row.status === 0 ? '未完成' : '已完成' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Notification" @click="showDetail(scope.row)" v-hasPermi="['manage:buylist:list']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:buylist:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:buylist:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 创建清单和修改清单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="buylistRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="清单名称" prop="listName">
          <el-input v-model="form.listName" placeholder="请输入清单名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品列表" prop="productList">
          <el-table :data="form.productList" style="width: 100%" :resizable="false" class="buylistTable">
            <el-table-column label="商品名称" prop="productName" align="center" width="160">
              <template #default="scope">
                <el-input v-model="scope.row.productName" placeholder="请输入商品名称" />
              </template>
            </el-table-column>
            <el-table-column label="商品图片" prop="productImage" align="center" width="80">
              <template #default="scope">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadFileUrl"
                  :show-file-list="false"
                  :headers="headers"
                  :on-error="handleUploadError"
                  :on-success="(response, file) => handleUploadSuccess(response, file, scope.$index)"
                  :before-upload="handleBeforeUpload"
                  :limit="1"
                  :on-remove="(file, fileList) => handleRemove(file, fileList, scope.$index)"
                >
                  <el-image v-if="scope.row.productImage" 
                    :src="scope.row.productImage" 
                    class="avatar"
                    @click.stop="handlePictureCardPreview(scope.row.productImage)"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="购买数量" prop="buyCount" align="center" width="200">
              <template #default="scope">
                <el-input-number v-model="scope.row.buyCount" :min="0.1" style="width: 90%;" :precision="1" :step="0.1" />
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unitId" align="center">
             <template #default="scope">
                <el-select v-model="scope.row.unitId" placeholder="请选择单位" clearable>
                  <el-option
                    v-for="dict in product_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="handleRemoveItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 按钮居中 -->
        </el-form-item>
        <div style="display: flex; justify-content: center;">
          <el-button  
            plain
            icon="CirclePlus"
            link
            type="primary"
            @click="handleAddItem">新增</el-button>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog
      v-model="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Buylist">
import { listBuylist, getBuylist, delBuylist, addBuylist, updateBuylist } from "@/api/manage/buylist";
import { getToken } from "@/utils/auth"

const { proxy } = getCurrentInstance()
const { product_unit } = proxy.useDict('product_unit')
console.log("product_unit", product_unit)

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const buylistList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    listId: null,
    listName: null,
    userId: null,
    remark: null,
    createTime: null,
    updateTime: null,
    status: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    listName: null,
    status: null
  },
  rules: {
    listName: [
      { required: true, message: "清单名称不能为空", trigger: "blur" }
    ],
    productList: [
      { 
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error('至少需要添加一个商品'));
          } else if (value.some(item => !item.productName || !item.buyCount || !item.unitId)) {
            callback(new Error('请完善所有商品信息'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询清单管理列表 */
function getList() {
  loading.value = true;
  listBuylist(queryParams.value).then(response => {
    buylistList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    listId: null,
    listName: null,
    userId: null,
    remark: null,
    createTime: null,
    updateTime: null,
    status: null,
    productList: []
  };
  proxy.resetForm("buylistRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.listId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "创建清单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _listId = row.listId || ids.value
  getBuylist(_listId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改清单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["buylistRef"].validate(valid => {
    if (valid) {
      // 额外验证商品列表是否有空数据
      if (form.value.productList && form.value.productList.some(
        item => !item.productName || !item.buyCount || !item.unitId
      )) {
        proxy.$modal.msgError("请完善所有商品信息");
        return;
      }
      
      if (form.value.listId != null) {
        console.log("修改清单数据", form.value);
        updateBuylist(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        })
      } else {
        addBuylist(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _listIds = row.listId || ids.value;
  const delName = _listIds.length >= 1 ? '选中的清单' : row.listName
  proxy.$modal.confirm('确定要删除' + delName + '吗？同时会删除该清单内的所有商品。').then(function() {
    return delBuylist(_listIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/buylist/export', {
    ...queryParams.value
  }, `buylist_${new Date().getTime()}.xlsx`)
}

// 新增商品
function handleAddItem() {
  form.value.productList.push({});
}

// 删除商品
function handleRemoveItem(index) {
  form.value.productList.splice(index, 1);
}

/** 上传地址 **/
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
/** 上传请求头 **/
const headers = ref({ "Authorization": "Bearer " + getToken() })

// 预览
function handlePictureCardPreview(url) {
  dialogImageUrl.value = url;
  dialogVisible.value = true;
}

// 删除图片的函数
const handleRemove = async (file, fileList, index) => {
  const row = form.value.productList[index];
  // 清除本地状态
  row.productImage = ''; // 清除图片链接
};

// 上传前loading加载
function handleBeforeUpload(file) {
  console.log("handleBeforeUpload", file);
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传图片，请稍候...");
  return true;
}

// 上传成功回调
function handleUploadSuccess(res, file, index) {
  console.log("handleUploadSuccess", res, file);
  if (res.code === 200) {
    // 获取服务器返回的图片URL
    const imageUrl = res.url; // 从res对象中获取图片URL
    form.value.productList[index].productImage = imageUrl;
  } else {
    proxy.$modal.msgError("图片上传失败");
  }
  proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传图片失败");
  proxy.$modal.closeLoading();
}

/** 上传前校验 **/
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: false
  },
});

// 查看详情跳转页面
function showDetail(row) {
  proxy.$router.push({
    path: '/shoplist/product',
    query: { listId: row.listId }
  });
}

getList();
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 40px;
  height: 40px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  text-align: center;
}
</style>

